<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : AdminActionLog.php
 * Created on : 2021-1-30 16:01:49
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace app\admin\model;

use think\Model;
use haoteam\service\NodeService;
use haoteam\service\AdminService;

/**
 * 
 * Class AdminActionLog
 * Tiger <1192851302@qq.com> 2021-1-30 16:01:49
 */
class AdminActionLog extends Model {

    /**
     * 获取数据列表-分页
     * @author Tiger <1192851302@qq.com>
     * @param array $where
     * @return array
     */
    public static function getList($where) {
        $model = new self;
        if (!empty($where['username'])) {
            $model = $model->where('username', 'LIKE', '%' . $where['username'] . '%');
            unset($where['username']);
        }
        if (!empty($where['node'])) {
            $model = $model->where('node', 'LIKE', '%' . $where['node'] . '%');
            unset($where['node']);
        }
        if (!empty($where['create_time'])) {
            [$start, $end] = explode(' - ', $where['create_time']);
            $model = $model->whereBetweenTime('create_time', $start, $end);
            unset($where['create_time']);
        }
        $model = $model->where($where)->order('create_time desc');
        $ip = new \Ip2Region();
        $models = $model->paginate(input('limit', 10))->each(function($item) use($ip) {
            $isp = $ip->btreeSearch($item->geoip);
            $item->isp = str_replace(['内网IP', '0', '|'], '', $isp['region'] ?? '');
        });
        return [
            'code' => 0,
            'items' => $models->items(),
            'total' => $models->total()
        ];
    }

    /**
     * 写入组装
     * @authr Tiger <1192851302@qq.com>
     * @param string $action
     * @param string $content
     * @return array
     */
    public static function write_bind_data(string $action, string $content) {
        return [
            'node' => NodeService::instance()->getCurrent(),
            'action' => $action, 'content' => $content,
            'geoip' => request()->ip() ?: '127.0.0.1',
            'username' => AdminService::instance()->getUsername(),
            'create_time' => date('Y-m-d H:i:s')
        ];
    }

    /**
     * 单次写入
     * @authr Tiger <1192851302@qq.com>
     * @param string $action
     * @param string $content
     * @return array
     */
    public static function _write(string $action, string $content) {
        return self::create(self::write_bind_data($action, $content));
    }
}
